/**
 *  使用  pnpm run li18n [token]
 *  eg.   pnpm run li18n VGh1QXByMTMwODozMDowN0NTVDIwMjMjQ0hFTkpJQVhJTkc=@
 *  token可选（可从header中自行获取）
 */

const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { chalk } = require('@vue/cli-shared-utils');
const { execSync } = require('child_process');

const log = {
  info(msg) {
    console.log(chalk.green(msg));
  },
  error(msg) {
    console.log(chalk.red(msg));
  },
  warnning(msg) {
    console.log(chalk.yellow(msg));
  }
};

function resolve(dir) {
  return path.join(__dirname, dir);
}

// 需要写入的文件路径
const filePaths = {
  en: resolve('../.i18nlocales/en.json'),
  'zh-CN': resolve('../.i18nlocales/zh-CN.json')
};

async function getDict(Authorization, lan = 'zh-CN') {
  // 创建axios实例
  const service = axios.create({
    baseURL: 'http://webcloudtest.byd.com.cn/icloudNew/api/',
    timeout: 60000,
    headers: {
      'Cache-Control': 'no-cache',
      Authorization
    }
  });

  const {
    data: { data }
  } = await service.get(`/msp-admin/lang/list?langType=${lan}`);
  return data;
}

async function writeJson(data, filePath) {
  const jsonStr = JSON.stringify(data);
  await fs.writeFileSync(filePath, jsonStr);
}

async function start(Authorization) {
  log.info('读取远程国际化资源和写入本地...');
  Object.entries(filePaths).forEach(async item => {
    const data = await getDict(Authorization, item[0]);
    await writeJson(data, item[1]);
    log.info('国际化文件写入本地目录完成, 正在格式化代码...');
    await execSync(`npx prettier --write ${item[1]}`);
  });
}

const Authorization = process.argv[2];
start(Authorization || 'VGh1QXByMTMwODozMDowN0NTVDIwMjMjQ0hFTkpJQVhJTkc=@');
